<?php
/**
 * View.php
 * Created by PhpStorm.
 * User: 江小波
 * Date: 2019/3/7
 * Time: 14:28
 */
namespace webapp\lib;

class View extends Response {
    /**
     * 模板输出变量
     * @var array tVar
     * @access protected
     */
    protected $tVar     =   [];

    /**
     * 模板输出内容
     * @var string content
     * @access protected
     */
    protected $content     =   "";

    public $charset = "utf-8";
    public $contentType = "text/html";

    public function send(){
        // 网页字符编码
        header('Content-Type:'.$this->contentType.'; charset='.$this->charset);
        header('Cache-control: private');  // 页面缓存控制
        header('X-Powered-By:webphp');
        // 输出模板
        exit($this->content);
    }

    /**
     * 模板变量赋值
     * @access public
     * @param mixed $name
     * @param mixed $value
     */
    public function assign($name,$value=''){
        if(is_array($name)) {
            $this->tVar   =  array_merge($this->tVar,$name);
        }else {
            $this->tVar[$name] = $value;
        }
        return $this;
    }

    /**
     * 取得模板变量的值
     * @access public
     * @param string $name
     * @return mixed
     */
    public function get($name=''){
        if('' === $name) {
            return $this->tVar;
        }
        return isset($this->tVar[$name])?$this->tVar[$name]:false;
    }

    /**
     * 取得模板内容
     * @access public
     * @return mixed
     */
    public function getContent(){
        return $this->content;
    }

    /**
     * 返回模板文件是否存在
     * @param string $tpl 模板字符串
     * @return bool|string
     */
    protected function isTplFile($tpl){
        $tpl = str_replace(["/","\\"],DS,$tpl).VIEW_EXT;
        if(!is_file($tpl)){
            if(THEME_NAME === ""){
                $tpl = VIEW_PATH.$tpl;
            }else{
                $tpl = VIEW_PATH.THEME_NAME.DS.$tpl;
            }
            if(is_file($tpl)){
                return $tpl;
            }
        }
        return false;
    }

    /**
     * 解析和获取模板内容 用于输出
     * @access public
     * @param string $templateFile 模板文件名
     * @param string $layoutFile 布局文件名
     * @return $this
     */
    public function fetch($templateFile='',$layoutFile='') {
        $templateFile = $this->isTplFile($templateFile);
        if($templateFile === false){
            $this->content = "";
            return $this;
        }
        // 页面缓存
        ob_start();
        ob_implicit_flush(0);
        // 模板阵列变量分解成为独立变量
        extract($this->tVar, EXTR_OVERWRITE);
        // 直接载入HTML模板
        include $templateFile;
        if(is_string($layoutFile) && $layoutFile !== ''){
            $layoutFile = $this->isTplFile($layoutFile);
            if($layoutFile !== false){
                include $layoutFile;
            }
        }
        // 获取并清空缓存
        $this->content = ob_get_clean();
        // 输出模板文件
        return $this;
    }
}